package com.san.oms.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.san.base.controller.BaseController;
import com.san.common.utils.Constant;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.R;
import com.san.oms.domain.ModelScDTO;
import com.san.oms.domain.QuotaDO;
import com.san.oms.domain.ScoreLevelDO;
import com.san.oms.service.ModelRoleService;
import com.san.oms.service.ModelService;
import com.san.oms.service.QuotaService;
import com.san.oms.service.ScoreLevelService;
import com.san.oms.vo.ModelVO;
import com.san.system.domain.UserDO;
import com.san.system.service.UserService;

/**
 * 评价模型业务控制类
 * 
 * @author xiangyz
 *
 */
@RequestMapping("/ce/model")
@Controller
public class ModelController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ModelController.class);

	private String PREFIX = "ce/model";

	@Autowired
	ModelService modelService;
	@Autowired
	private QuotaService quotaService;
	@Autowired
	private ScoreLevelService scoreLevelService;

	@Autowired
	private ModelRoleService modelRoleService;

	@Autowired
	UserService userService;

	@GetMapping("")
	@RequiresPermissions("ce:model:view")
	String source(Model model) {
		return PREFIX + "/view";
	}

	@GetMapping("/list")
	@RequiresPermissions("ce:model:view")
	@ResponseBody
	public PageUtils findModel(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			Query query = new Query(params);
			pageUtils = modelService.findModel(query);
		} catch (Exception e) {
			logger.error("获取模型分页数据出错", e);
		}

		return pageUtils;
	}

	@GetMapping("/add")
	@RequiresPermissions("ce:model:add")
	String add(Model model) {
		return PREFIX + "/add";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("ce:model:add")
	public R save(ModelVO vo) {
		boolean check = checkModelName(vo);
		if (!check) {
			return R.error("模型名称已存在");
		}
		try {
			if (modelService.save(vo) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("保存数据出错", e);
		}
		return R.error();
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("ce:model:edit")
	String edit(Model model, @PathVariable("id") Long id) {
		try {
			ModelScDTO modelScDTO = (ModelScDTO) modelService.getById(id);
			model.addAttribute("modelScDTO", modelScDTO);
		} catch (Exception e) {
			logger.error("编辑时获取模型数据出错", e);
		}
		return PREFIX + "/edit";
	}

	@PostMapping("/doEdit")
	@RequiresPermissions("ce:model:edit")
	@ResponseBody
	R doEdit(ModelVO vo) {
		boolean check = checkModelName(vo);
		if (!check) {
			return R.error("模型名称已存在");
		}
		Map<String, Object> map = new HashMap<>();
		map.put("modelId", vo.getModelId());
		int score = 0;
		try {
			List<QuotaDO> list = quotaService.findQuotaList(map);
			for (QuotaDO quotaDO : list) {
				if (quotaDO.getParentId() == null || quotaDO.getParentId() == 0) {
					score += quotaDO.getQuotaScore();
				}
			}
			ScoreLevelDO scoreLevelDO = scoreLevelService.getById(vo.getScoreId());
			if (scoreLevelDO.getScoreTotal() < score) {
				return R.error("模型总分小于指标总分，修改失败");
			}
			if (modelService.doEdit(vo) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("更新模型数据出错", e);
		}
		return R.error();
	}

	@PostMapping("/remove")
	@RequiresPermissions("ce:model:remove")
	@ResponseBody
	R remove(Long id) {
		try {
			if (modelService.remove(id) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("删除模型数据出错", e);
		}
		return R.error();
	}

	@PostMapping("/batchRemove")
	@RequiresPermissions("ce:model:batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] ids) {
		try {
			if (modelService.batchRemove(ids) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("批量删除模型数据出错", e);
		}

		return R.error();
	}

	/**
	 * 校验模型名称
	 * 
	 * @param vo
	 * @return
	 */
	public boolean checkModelName(ModelVO vo) {
		boolean result = true;
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("modelName", vo.getModelName());
			List<ModelScDTO> modelList = modelService.findModelList(new Query(condition));
			for (ModelScDTO modelDO : modelList) {
				if (null == vo.getModelId() || vo.getModelId() == 0) {
					// 新增时，只需要判断名称在数据库中是否存在
					if (vo.getModelName().trim().equals(modelDO.getModelName())) {
						result = false;
						break;
					}
				} else {
					// 修改时，需要排除自身数据
					if (vo.getModelName().trim().equals(modelDO.getModelName())
							&& vo.getModelId().longValue() != modelDO.getModelId().longValue()) {
						result = false;
						break;
					}
				}
			}
		} catch (Exception e) {
			result = false;
			logger.error("校验模型名称出错", e);
		}

		return result;
	}

	@PostMapping("/findModelList")
	@ResponseBody
	public R findModelList(@RequestParam Map<String, Object> params) {
		params.put("delFlag", Constant.DEL_FLAG_NORMAL);
		List<ModelScDTO> list = null;

		UserDO userDO;
		List<Long> modelIds = null;
		try {
			userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			modelIds = modelRoleService.modelList(deptId);
		} catch (Exception e) {
			logger.error("获取用户角色失败", e);
			R r = new R();
			r.put("code", 0);
			r.put("msg", "查询失败");
			r.put("obj", "");
			return r;
		}

		list = modelService.findModelList(new Query(params));
		List<ModelScDTO> resultList = new ArrayList<ModelScDTO>();
		for (ModelScDTO i : list) {
			if (modelIds.contains(i.getModelId())) {
				resultList.add(i);
			}
		}

		R r = new R();
		r.put("code", 0);
		r.put("msg", "查询成功");
		r.put("obj", resultList);

		return r;
	}
}
